<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽框</title>
    <style>
        #box{
            width: 240px;
            height: 240px;
            border: 1px solid #cccccc;
            border-radius: 5px;
            overflow: hidden;
            background: rgb(241, 241, 231);
            position: absolute;
        }
        #box .title{
            padding: 0px 5px;
            height: 30px;
            background:rgb(153, 153, 120);
            display:flex;
            justify-content: space-between;
            align-items: center;
            cursor: move;
            user-select: none;
        }
        #box .title .close{
            width: 20px;
            height: 20px;
            border-radius: 20px;
            border: 1px solid #cccccc;
            text-align: center;
            cursor: default;
        }
    </style>
</head>
<body>
    <div id="box">
        <div class="title">
           <div>拖拽框</div>
           <div class="close">X</div>
        </div>
        <div class="content">
            HelloWorld
        </div>
    </div>
    <script>
        let box = document.querySelector("#box")
        let title = document.querySelector(".title")
        let close = document.querySelector(".close")

        //关闭
        close.onclick = function(){
            box.remove()
        }

        let canMove = false  //是否可以移动

        let x = 0  //鼠标点击处距离box左边框的距离
        let y = 0  //鼠标点击处距离box上边框的距离
        //title注册鼠标按下事件
        title.onmousedown = function(e){
            canMove = true   //可以移动
            x = e.pageX - box.offsetLeft
            y = e.pageY - box.offsetTop
        }

        //window注册鼠标弹起事件
        window.onmouseup = function(){
            canMove = false  //不可以移动
        }

        //window注册失去焦点事件
        window.onblur = function(){
            canMove = false  //不可以移动
        }
       
        //window注册鼠标移动事件
        window.onmousemove = function(e){
            if(canMove){
                //box的最新left值
                let left = e.pageX - x;
                if(left<0) left = 0
                //box的最新top值
                let top = e.pageY - y
                if(top<0) top = 0
                
                //offsetWidth属性返回元素可见宽度
                //offsetLeft属性返回元素距离最近的定位父级元素的X轴位置
                //window.innerWidth 返回窗体的可见宽度

                //算出box可以移动的最大距离
                let maxLeft = window.innerWidth - box.offsetWidth
                let maxTop = window.innerHeight - box.offsetHeight
                if(left > maxLeft) left = maxLeft
                if(top > maxTop) top = maxTop

                box.style.left = left +'px'
                box.style.top = top +'px'
            }
        }
    </script>
</body>
</html>